<template lang="pug">
.pageL-list-import
  el-dialog(title="导入" v-model="dialogVisible" @close="handleClose" custom-class="dialog-width")
    el-scrollbar.scrollbar-dialog-wrap.excel-import-main

      .import-ts 导入的数据必须与模板的格式相同，不然会出现未知错误。
        span.span(@click="handleDownload") 下载模板

      .upload-wrap
        el-upload(class="upload-demo" ref="upload" :on-change="handleChange" :file-list="state.fileList" :auto-upload="false" action="")
          el-button(size="small" slot="trigger" type="primary") 选取文件
          el-button(size="small" type="success" :loading="loading" @click.stop="formSubmit") 点击上传
</template>

<script setup>
import { fileDownload } from '../../api/comment'

import { ref, reactive, getCurrentInstance, watch, defineProps, defineEmit } from 'vue'

const { proxy } = getCurrentInstance()
const emit = defineEmit(['closeFun', 'update:isDialog'])
const props = defineProps({
  isDialog: {
    required: true
  }
})

const state = reactive({
  fileList: []
})
const dialogVisible = ref(false)
const loading = ref(false)

// 侦听
watch(() => [props.isDialog], ([newDialog, oldDialog]) => {
  if (!newDialog) return

  state.fileList = []
  dialogVisible.value = newDialog
}, { immediate: true })

// 选择文件
function handleChange (file, fileList) {
  const isJPG = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.raw.type === 'application/vnd.ms-excel' || file.raw.name.indexOf('.csv') > -1 || file.raw.name.indexOf('.excel') > -1 || file.raw.name.indexOf('.xlsx') > -1
  if (!isJPG) {
    state.fileList = fileList.slice(-1)
    proxy.$message({ type: 'error', message: '上传文件类型为xls！' })
  } else {
    state.fileList = fileList.slice(-1)
  }
  return isJPG
}

// 下载模板
function handleDownload () {
  const query = {
    id: 1
  }
  fileDownload(query)
}

// 表达提交
function formSubmit () {
  loading.value = true

  const param = new FormData()

  state.fileList.forEach((val) => {
    param.append('files', val.raw, val.raw.name)
  })

  console.log(state.fileList)
  console.log(param)
  // proxy.$message({ type: 'success', message: '提交成功' })
  // emit('closeFun')
  // handleClose()
}

// 关闭弹窗
function handleClose () {
  emit('update:isDialog', false)
  dialogVisible.value = false
}
</script>
<style rel="stylesheet/scss" lang="scss">
</style>
